package org.packtracker.server.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;

import org.packtracker.server.Utils;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.webharvest.definition.ScraperConfiguration;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class TrackerService {
	private static final Logger log = Logger.getLogger(TrackerService.class.getName());

	private Vector<HashMap<String, Object>> trackers;
	private HashMap<String, ScraperConfiguration> scraperConfig;

	TrackerService() {
		scraperConfig = new HashMap<String, ScraperConfiguration>();
		try {
			trackers = parseTrackerConfig(TrackerService.class.getResourceAsStream("/config/packtracker.xml"));
		} catch(Exception e) {
			throw new RuntimeException("Could not load trackers from config file", e);
		}
		log.info("Loaded " + trackers.size() + " trackers from config");
	}

	public Vector<String> getTrackerNames() {
		Vector<String> names = new Vector<String>();
		for(HashMap<String, Object> tracker : trackers) {
			names.add((String) tracker.get("name"));
		}
		Collections.sort(names);
		return names;
	}
	
	private Vector<HashMap<String, Object>> parseTrackerConfig(InputStream configStream) throws SAXException, IOException, ParserConfigurationException {
		Vector<HashMap<String, Object>> list = new Vector<HashMap<String, Object>>();
		Document doc = Utils.parseXmlFile(new InputSource(configStream), false);
		NodeList siteList = doc.getElementsByTagName("tracker");
		for (int n = 0; n < siteList.getLength(); n++) {
			Node node = siteList.item(n);
			NamedNodeMap attrs = node.getAttributes();
			HashMap<String, Object> tracker = new HashMap<String, Object>();
			tracker.put("name", attrs.getNamedItem("name").getNodeValue());
			log.info("Reading config for site " + tracker.get("name"));
			tracker.put("scrapeConfig", attrs.getNamedItem("scrapeConfig").getNodeValue());
			tracker.put("country", attrs.getNamedItem("country").getNodeValue());
			tracker.put("dateTimePattern", attrs.getNamedItem("dateTimePattern").getNodeValue());
			tracker.put("mainUrl", attrs.getNamedItem("mainUrl").getNodeValue());
			tracker.put("trackUrl", attrs.getNamedItem("trackUrl").getNodeValue());
			tracker.put("order", attrs.getNamedItem("order").getNodeValue());
			tracker.put("ems", Boolean.parseBoolean(attrs.getNamedItem("ems").getNodeValue()));
			list.add(tracker);
		}
		return list;
	}

}
